package br.ucb.tcc.negocio;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import twitter4j.DirectMessage;
import twitter4j.GeoLocation;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import br.ucb.tcc.entidades.Perfil;
import br.ucb.tcc.utils.StringUtil;

/**
 * @author italoricci
 * 
 */

// TODO �talo -  Sao apenas 350 requisicoes por hour


public class TwitterBean {

	public static Twitter twitter;

	public static boolean autentica(String consumerKey, String consumerSecret) {

		// ConfigurationBuilder configurationBuilder = new
		// ConfigurationBuilder();
		// configurationBuilder.setOAuthConsumerKey(FileUtils.lerValorProperties(
		// Constantes.PATH, Constantes.NOME_ARQUIVO, "oauth.consumerKey"));
		// configurationBuilder.setOAuthConsumerSecret(FileUtils
		// .lerValorProperties(Constantes.PATH, Constantes.NOME_ARQUIVO,
		// "oauth.consumerSecret"));

		ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
		configurationBuilder.setOAuthConsumerKey(consumerKey);
		configurationBuilder.setOAuthConsumerSecret(consumerSecret);

		Configuration configuration = configurationBuilder.build();

		try {
			AccessToken accessToken = getTwitter(configuration).getOAuthAccessToken();
			String token = accessToken.getToken();
			String tokenSecret = accessToken.getTokenSecret();

			if (token == null || tokenSecret == null) {
				return false;
			}
		} catch (TwitterException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public static Twitter getTwitter(Configuration conf) {
		if (twitter == null) {
			twitter = new TwitterFactory(conf).getInstance();
		}
		return twitter;
	}

	public static void sendMessage(String mensagem) throws TwitterException {
		twitter.updateStatus(mensagem);
	}

	public static List<Tweet> buscarTwitterPorAssunto(String assunto) throws TwitterException {
		List<Tweet> tweets = null;
		Query query = new Query(assunto);
		QueryResult queryResult = twitter.search(query);
		query.setPage(4);
		tweets = queryResult.getTweets();
		return tweets;
	}
	
	public static List<Tweet> buscarTwitterPorAssuntoPorLocalizacao(String assunto,
			Double latitude, Double longintude, Double raio, String unidadeMedida)
			throws TwitterException {
		List<Tweet> tweets = null;
		Query query = new Query(assunto);
		query.setGeoCode(new GeoLocation(latitude, longintude), raio, unidadeMedida);
		QueryResult queryResult = twitter.search(query);

		tweets = queryResult.getTweets();
		return tweets;
	}

	public static void sendDirectMessage(String nome, String assunto) throws TwitterException {
		ResponseList<User> obterUsuarioPorQuery = obterUsuarioPorQuery(nome);
		DirectMessage sendDirectMessage = twitter.sendDirectMessage(obterUsuarioPorQuery.get(0)
				.getId(), assunto);
		System.out.println(sendDirectMessage.getText());
	}

	public static User obterUsuarioPeloNome(String screenNameUsuario) throws TwitterException {
		return twitter.showUser(screenNameUsuario);
	}

	public static User obterUsuarioPeloId(long l) throws TwitterException {
		return twitter.showUser(l);
	}

	public static ResponseList<User> obterUsuarioPorQuery(String query) throws TwitterException {
		return twitter.searchUsers(query, 0);
	}

	public static ResponseList<Status> obterTimeLineAmigos() throws TwitterException {
		return twitter.getFriendsTimeline();
	}

	public static ResponseList<Status> obterHomeTimeLine() throws TwitterException {
		return twitter.getHomeTimeline();
	}

	public static List<Tweet> getTweetsPorStatusOrRT(String assunto, Integer quantidade) throws TwitterException {
		List<Tweet> tweets = new ArrayList<Tweet>();
		Query query = new Query(assunto);
		for (int i = 1; i < quantidade; i++) {
			query.setPage(i);
			QueryResult queryResult = twitter.search(query);
			tweets.addAll(queryResult.getTweets());
		}
		return tweets;
	}

	public static String obterNome() throws IllegalStateException, TwitterException {
		return twitter.getScreenName();
	}
	
	public static Map<Long, Long> obterMapsRelacao(List<Tweet> twwets) {
		Map<Long, Long> mapsCodigos = new HashMap<Long, Long>();
		for (Tweet tweet : twwets) {
			if (tweet.getToUserId() != -1) {
				mapsCodigos.put(tweet.getFromUserId(), tweet.getToUserId());
			} else {
				String obterNomeRT = StringUtil.retornarNomePrincipal(tweet.getText(), "@");
				User userRT;
				try {
					userRT = twitter.showUser(obterNomeRT);
					mapsCodigos.put(tweet.getFromUserId(), userRT.getId());
				} catch (TwitterException e) {
					e.printStackTrace();
					continue;
				}
			}
		}
		return mapsCodigos;
	}

	public static Perfil montarPerfilDTO(Tweet tweet) throws TwitterException {
		Perfil perfilDTO = null;
		perfilDTO = montarPerfilDTO(twitter.showUser(tweet.getFromUserId()));
		return perfilDTO;
	}

	public static Perfil montarPerfilDTO(Long id) throws TwitterException {
		Perfil perfilDTO = null;
		perfilDTO = montarPerfilDTO(twitter.showUser(id));
		return perfilDTO;
	}

	public static Perfil montarPerfilDTO(User user) {
		Perfil dto = new Perfil();
		dto.setId(user.getId());
		dto.setLocalizacao(user.getLocation());
		dto.setCorFundo(user.getProfileBackgroundColor());
		dto.setDescricaoPerfil(user.getDescription());
		dto.setCorLink(user.getProfileLinkColor());
		dto.setNomeExibicao(user.getScreenName());
		dto.setNomePerfil(user.getName());
		dto.setQtdAmigos(user.getFriendsCount());
		dto.setQtdSeguidores(user.getFollowersCount());
		dto.setUltimoPost(user.getStatus() != null ? user.getStatus().getText() : "Post Inativo");
		dto.setUrlBackground(user.getProfileBackgroundImageUrl());
		dto.setUrlImagem(user.getProfileImageURL().getPath());
		return dto;
	}

	public static Perfil montarPerfilDTO(User user, String text) {
		Perfil perfilDTO = null;
		perfilDTO = montarPerfilDTO(user);
		perfilDTO.setUltimoPost(text);
		return perfilDTO;
	}

	public static StringBuilder formatarNomes(ResponseList<User> query) {
		StringBuilder stringBuilder = new StringBuilder();
		for (User user : query) {
			stringBuilder.append(user.getScreenName() + "\n");
		}
		return stringBuilder;
	}

	public static StringBuilder formatarNomesEncontrados(Map<Long, Long> obterMapsRelacao)
			throws TwitterException {
		StringBuilder sb = new StringBuilder();
		for (Long key : obterMapsRelacao.keySet()) {
			String nome1 = obterUsuarioPeloId(key).getScreenName();
			String nome2 = obterUsuarioPeloId(obterMapsRelacao.get(key)).getScreenName();
			sb.append("Origem >" + nome1 + " Destino> " + nome2 + "\n");
		}
		return sb;
	}

	public static StringBuilder formatarRelacoes(Map<Long, Long> obterMapsRelacao)
			throws TwitterException {
		StringBuilder sb = new StringBuilder();
		for (Long key : obterMapsRelacao.keySet()) {
			String nome1 = obterUsuarioPeloId(key).getScreenName();
			String nome2 = obterUsuarioPeloId(obterMapsRelacao.get(key)).getScreenName();
			sb.append("Origem >" + nome1 + " Destino> " + nome2 + "\n");
		}
		return sb;
	}

	public static StringBuilder getListaTimeLineFormatada() throws TwitterException {
		ResponseList<Status> obterHomeTimeLine = obterHomeTimeLine();
		StringBuilder sb = new StringBuilder();
		for (Status status : obterHomeTimeLine) {
			sb.append(status.getText() + "\n");
		}
		return sb;
	}
}
